import { createRouter, createWebHistory } from 'vue-router'
import { getCurrentUser } from '@/utils/auth'

const VideoHome = () => import('../views/VideoHome.vue')
const WatchView = () => import('../views/WatchView.vue')
const Login = () => import('../views/Login.vue')
const Register = () => import('../views/Register.vue')

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', name: 'home', component: VideoHome, meta: { title: 'StreamVue - 视频站' } },
    { path: '/watch/:id', name: 'watch', component: WatchView, meta: { title: '播放 - StreamVue' } },
    { path: '/author/:name', name: 'author', component: () => import('@/views/AuthorView.vue'), meta: { title: '作者主页 - StreamVue' } },
    { path: '/login', name: 'login', component: Login, meta: { title: '登录 - StreamVue' } },
    { path: '/register', name: 'register', component: Register, meta: { title: '注册 - StreamVue' } },
    { path: '/profile', name: 'profile', component: () => import('@/views/Profile.vue'), meta: { title: '个人中心', requiresAuth: true } },
    { path: '/member', name: 'member', component: () => import('@/views/EnhancedMemberCenter.vue'), meta: { title: '会员中心', requiresAuth: true } },
    { path: '/test-nav', name: 'testNav', component: () => import('@/views/TestNav.vue'), meta: { title: '导航测试' } },
    { path: '/:pathMatch(.*)*', redirect: '/' }
  ],
  scrollBehavior() {
    return { top: 0 }
  }
})

router.beforeEach((to, from, next) => {
  // 标题
  if (to.meta && to.meta.title) {
    document.title = `Vue 视频站 - ${to.meta.title}`
  }
  
  // 简化的认证守卫
  const needAuth = !!to.meta?.requiresAuth
  const user = getCurrentUser()
  
  if (needAuth && !user) {
    return next({ path: '/login', query: { redirect: to.fullPath } })
  }
  
  next()
})

export default router